package com.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.enums.BizCodeEnum;
import com.model.LoginUser;
import com.utils.CommonUtil;
import com.utils.JsonData;
import com.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author rkc
 * @date 2022/8/24 10:35
 */
@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("token");
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getParameter("token");
        }
        if (StringUtils.isBlank(accessToken)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }
        //token不为空，进行检测
        Claims claims = JwtUtil.checkJWT(accessToken);
        if (Objects.isNull(claims)) {
            CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UN_LOGIN));
            return false;
        }
        Integer uid = Integer.parseInt(claims.get("uid").toString());
        String username = claims.get("username", String.class);
        String headImg = claims.get("head_img", String.class);
        LoginUser loginUser = LoginUser.builder().uid(uid).username(username).headImg(headImg).build();
        THREAD_LOCAL.set(loginUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }
}